package cn.leedsoft.luma.controller;

import cn.leedsoft.luma.common.utils.RequestUtil;
import cn.leedsoft.luma.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;

/**
 * Created by leeds on 2016/6/28 10:57.
 */
@ControllerAdvice
public class ControllerAdvisor {
    private static final Logger logger = LoggerFactory.getLogger(ControllerAdvisor.class);

    @ExceptionHandler({Exception.class})
    public ModelAndView handleEx(HttpServletRequest request, Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("errmsg", e.getMessage());
        logger.error(e.getMessage(), e);
        if (RequestUtil.isAjax()) {
            mv.setViewName("/error/ajax");
        } else {
            mv.setViewName("error/html");
        }
        return mv;
    }

    @InitBinder//spring mvc自定义接收日期参数
    public void initBind(WebDataBinder binder, Locale locale) {
        //Date parameter conversion
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                if (StringUtils.isBlank(text)) {
                    throw new IllegalArgumentException();
                }

                //yyyy-MM-dd
                String regDate = "\\d{4}-([1-9]|0[1-9]|1[0-2])-([1-9]|[01][1-9]|3[01])";
                //HH:mm:ss 日期默认是今天
                String regTime = "([0-1]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";
                //HH:mm 日期默认是今天
                String regTime2 = "([0-1]\\d|2[0-3]):[0-5]\\d";
                //yyyy-MM-dd HH:mm:ss
                String regDateTime = regDate + "\\s" + regTime;
                //yyyy-MM-dd HH:mm
                String regDateTime2 = regDate + "\\s" + regTime2;
                //Unix 10位 时间戳 从1970-01-01 00:00:00到现在的秒数
                String timestamp10 = "\\d{10}";
                //Unix 13位 时间戳 从1970-01-01 00:00:00到现在的毫秒数
                String timestamp13 = "\\d{13}";

                DateFormatter dateFormatter = null;
                Long time = null;
                Date res = new Date();
                if (text.matches(regDateTime)) {
                    dateFormatter = new DateFormatter("yyyy-MM-dd HH:mm:ss");
                } else if (text.matches(regDateTime2)) {
                    dateFormatter = new DateFormatter("yyyy-MM-dd HH:mm");
                } else if (text.matches(regDate)) {
                    dateFormatter = new DateFormatter("yyyy-MM-dd");
                } else if (text.matches(regTime)) {
                    dateFormatter = new DateFormatter("yyyy-MM-dd HH:mm:ss");
                    text = new DateFormatter("yyyy-MM-dd").print(new Date(), locale).concat(" " + text);
                } else if (text.matches(regTime2)) {
                    dateFormatter = new DateFormatter("yyyy-MM-dd HH:mm");
                    text = new DateFormatter("yyyy-MM-dd").print(new Date(), locale).concat(" " + text);
                } else if (text.matches(timestamp13)) {
                    time = Long.parseLong(text);
                } else if (text.matches(timestamp10)) {
                    time = Long.parseLong(timestamp10) * 1000;
                }
                if (dateFormatter != null) {
                    try {
                        res = dateFormatter.parse(text, locale);
                    } catch (ParseException e) {
                        e.printStackTrace();
                        throw new IllegalArgumentException(e);
                    }
                } else if (time != null) {
                    res.setTime(time);
                } else {
                    throw new IllegalArgumentException();
                }
                setValue(res);
            }
        });
    }
}